'''
Description: 
Author: HowsenFisher
Date: 2021-04-12 09:52:30
LastEditTime: 2021-04-12 16:15:03
LastEditors: liutq
Reference: 
'''
import socket,pyaudio
from Media.Voice.VoicePlayer import VoicePlayer
from threading import Thread
from multiprocessing import Process
import cv2

class VoiceReceiver:
    def __init__(self,parent,ip,port):
        print("初始化声音播放器")
        self.p = pyaudio.PyAudio()
        self.chunk_size = 1024 # 512
        self.audio_format = pyaudio.paInt16
        self.channels = 2
        self.rate = 44100
        self.playing_stream = self.p.open(format=self.audio_format,
                                            channels=self.channels,
                                            rate=self.rate,
                                            output=True,
                                            frames_per_buffer=self.chunk_size)
        print("声音播放器初始化完毕完毕")
        print("声音接收器初始化")
        # Process.__init__(self)
        self.parent = parent
        # self.parent.newInfoSignal.emit("初始化音频接收器")
        self.ip = ip
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.ip,self.port))
        self.s.listen(255)
        while True:
            if self.run()=="stop":
                break

    def run(self):
        self.client,addr = self.s.accept()
        print("声音接收器：",addr)
        while True:
            try:
                voiceData = self.client.recv(2048)
                # print("voiceData")
                # if voiceData == b'':
                #     print(voiceData)
                #     break
                if voiceData==b'stop' or voiceData==b'':
                    break
            except Exception:
                break
            self.playing_stream.write(voiceData)

if __name__ == '__main__':
    myVoiceReceiver = VoiceReceiver("0.0.0.0",911)
    myVoiceReceiver.start()
